<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部搜索和筛选区域 -->
    <div class="bg-white shadow-sm sticky top-0 z-10">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <!-- 搜索栏 -->
        <div class="flex items-center space-x-4 mb-4">
          <div class="relative flex-1">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <UIcon name="i-heroicons-magnifying-glass" class="h-5 w-5 text-gray-400" />
            </div>
            <input
              type="text"
              placeholder="搜索作品、标签或作者"
              v-model="searchQuery"
              class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
              @keyup.enter="handleSearch"
            />
          </div>
          <UButton
            color="primary"
            @click="handleSearch"
          >
            搜索
          </UButton>
        </div>

        <!-- 分类标签导航 -->
        <div class="flex space-x-8 overflow-x-auto pb-1 scrollbar-hide">
          <button
            v-for="tab in tabs"
            :key="tab.id"
            :class="[
              'py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap',
              activeTab === tab.id
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            ]"
            @click="activeTab = tab.id"
          >
            {{ tab.name }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 标签筛选区域 -->
    <div class="bg-white border-t border-gray-100 shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
        <div class="flex flex-wrap gap-2">
          <UBadge
            v-for="tag in popularTags"
            :key="tag.id"
            :color="selectedTags.includes(tag.id) ? 'primary' : 'gray'"
            variant="soft"
            class="cursor-pointer"
            @click="toggleTag(tag.id)"
          >
            {{ tag.name }}
          </UBadge>
        </div>
      </div>
    </div>
    
    <!-- 排序选项 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
      <div class="text-sm text-gray-500">
        共找到 <span class="font-medium text-gray-900">{{ totalItems }}</span> 个作品
      </div>
      <USelectMenu
        v-model="sortOption"
        :options="sortOptions"
        placeholder="排序方式"
        class="w-40"
      />
    </div>

    <!-- 精品作品展示 -->
    <div class="bg-white py-8">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <h2 class="text-2xl font-bold text-gray-900 mb-6">精品作品展示</h2>
        <div class="relative">
          <!-- 轮播图容器 -->
          <div class="overflow-hidden">
            <div 
              class="flex transition-transform duration-500 ease-in-out" 
              :style="{ transform: `translateX(-${currentSlide * (100 / 3)}%)` }"
            >
              <div 
                v-for="(board, index) in featuredBoards" 
                :key="board.id"
                class="w-1/3 flex-shrink-0 px-2"
              >
                <div class="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-200">
                  <div class="relative aspect-w-16 aspect-h-10">
                    <NuxtImg 
                      :src="board.images[0]?.img_url" 
                      :alt="board.title" 
                      class="object-cover w-full h-full" 
                      loading="eager" 
                      priority 
                      placeholder 
                      format="avif,webp" 
                      quality="80"
                      :modifiers="{
                        width: 800,
                        height: 600,
                        fit: 'cover',
                      }"
                    />
                  </div>
                  <div class="p-4">
                    <h3 class="text-lg font-medium text-gray-900 mb-2">{{ board.title }}</h3>
                    <p class="text-sm text-gray-500 line-clamp-2">{{ board.description }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 轮播控制按钮 -->
          <button 
            class="absolute left-0 top-1/2 -translate-y-1/2 bg-white/80 p-2 rounded-full shadow-md hover:bg-white"
            @click="prevSlide"
          >
            <UIcon name="i-heroicons-chevron-left" class="h-6 w-6 text-gray-600" />
          </button>
          <button 
            class="absolute right-0 top-1/2 -translate-y-1/2 bg-white/80 p-2 rounded-full shadow-md hover:bg-white"
            @click="nextSlide"
          >
            <UIcon name="i-heroicons-chevron-right" class="h-6 w-6 text-gray-600" />
          </button>

          <!-- 轮播指示器 -->
          <div class="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2">
            <button
              v-for="(_, index) in featuredBoards"
              :key="index"
              class="w-2 h-2 rounded-full transition-colors duration-200"
              :class="currentSlide === index ? 'bg-primary-600' : 'bg-gray-300'"
              @click="currentSlide = index"
            ></button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分隔线和社区作品标题 -->
    <div class="border-t border-gray-200 mt-12">
      <h2 class="text-2xl font-bold text-gray-900 text-center my-8">社区用户作品展示</h2>
    </div>

    <!-- 瀑布流内容 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <div v-if="loading" class="flex justify-center py-12">
        <UIcon name="i-heroicons-arrow-path" class="h-10 w-10 animate-spin text-primary-600" />
      </div>
      
      <div v-else-if="posts.length === 0" class="text-center py-16">
        <UIcon name="i-heroicons-photo" class="h-16 w-16 mx-auto text-gray-300" />
        <h3 class="mt-4 text-lg font-medium text-gray-900">暂无作品</h3>
        <p class="mt-2 text-sm text-gray-500">尝试更改搜索条件或浏览其他分类</p>
      </div>
      
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <!-- 作品卡片 -->
        <div 
          v-for="post in posts" 
          :key="post.id" 
          class="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-all duration-300 hover:-translate-y-1"
        >
          <!-- 作品图片 -->
          <div class="relative overflow-hidden" :style="{ paddingBottom: `${post.aspectRatio ? post.aspectRatio * 100 : 75}%` }">
            <NuxtImg 
              :src="post.imageUrl" 
              :alt="post.title" 
              class="absolute inset-0 w-full h-full object-cover transition-transform duration-500 hover:scale-105" 
              loading="lazy" 
              placeholder 
            />
          </div>
          
          <!-- 作品信息 -->
          <div class="p-4">
            <div class="flex items-center space-x-3 mb-3">
              <UAvatar
                size="sm"
                :src="userInfo?.avatar || post.author.avatar"
                :alt="post.author.name"
              />
              <div>
                <h3 class="text-sm font-medium text-gray-900">{{ post.author.name }}</h3>
                <p class="text-xs text-gray-500">{{ post.createdAt }}</p>
              </div>
            </div>
            
            <h2 class="text-lg font-medium text-gray-900 mb-2">{{ post.title }}</h2>
            <p class="text-sm text-gray-500 mb-4">{{ post.description }}</p>
            
            <!-- 标签 -->
            <div v-if="post.tags" class="flex flex-wrap gap-1 mb-3">
              <UBadge 
                v-for="tag in post.tags" 
                :key="tag.id" 
                color="gray" 
                variant="soft" 
                size="xs"
                class="cursor-pointer hover:bg-gray-200"
                @click="addTagFilter(tag.id)"
              >
                {{ tag.name }}
              </UBadge>
            </div>
            
            <!-- 互动区域 -->
            <div class="flex items-center justify-between text-sm text-gray-500">
              <div class="flex items-center space-x-4">
                <button class="flex items-center space-x-1 hover:text-primary-600" @click="handleLike(post.id)">
                  <UIcon :name="post.isLiked ? 'i-heroicons-heart-solid' : 'i-heroicons-heart'" class="h-5 w-5" />
                  <span>{{ post.likes }}</span>
                </button>
                <button class="flex items-center space-x-1 hover:text-primary-600" @click="handleComment(post.id)">
                  <UIcon name="i-heroicons-chat-bubble-left" class="h-5 w-5" />
                  <span>{{ post.comments }}</span>
                </button>
              </div>
              <UDropdown
                :items="postMenuItems"
                :ui="{ item: { base: 'flex items-center gap-2 cursor-pointer' } }"
              >
                <UButton color="gray" variant="ghost" icon="i-heroicons-ellipsis-horizontal" />
              </UDropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMoreItems && !loading" class="flex justify-center mt-8 mb-12">
        <UButton
          color="gray"
          variant="soft"
          @click="loadMoreData"
          :loading="loadingMore"
        >
          加载更多
        </UButton>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { api } from '~/utils/api'

interface UserInfo {
  id: string
  username: string
  nickname: string
  gender: string
  phone: string
  avatar: string
  status: number
  description: string
}

const userInfo = ref<UserInfo | null>(null)

// 搜索和筛选状态
const searchQuery = ref('')
const activeTab = ref('overview')
const selectedTags = ref<string[]>([])
const sortOption = ref('latest')

// 加载状态
const loading = ref(true)
const loadingMore = ref(false)
const page = ref(1)
const hasMoreItems = ref(true)
const totalItems = ref(0)

// 标签页数据
const tabs = [
  // 已移除总览、演示和标注选项
]

// 热门标签
const popularTags = ref([
  { id: 'sunset', name: '日落' },
  { id: 'mountains', name: '山脉' },
  { id: 'beach', name: '海滩' },
  { id: 'city', name: '城市' },
  { id: 'forest', name: '森林' },
  { id: 'portrait', name: '人像' },
  { id: 'travel', name: '旅行' },
  { id: 'minimalist', name: '极简' },
  { id: 'vintage', name: '复古' },
  { id: 'night', name: '夜景' }
])

// 排序选项
const sortOptions = [
  { value: 'latest', label: '最新发布' },
  { value: 'popular', label: '最受欢迎' },
  { value: 'trending', label: '热门趋势' },
  { value: 'oldest', label: '最早发布' }
]

// 监听筛选条件变化
watch([activeTab, selectedTags, sortOption], () => {
  resetAndFetch()
})

// 搜索处理
const handleSearch = () => {
  resetAndFetch()
}

// 重置并获取数据
const resetAndFetch = () => {
  page.value = 1
  loading.value = true
  hasMoreItems.value = true
  posts.value = []
  fetchPosts()
}

// 切换标签选择
const toggleTag = (tagId: string) => {
  const index = selectedTags.value.indexOf(tagId)
  if (index === -1) {
    selectedTags.value.push(tagId)
  } else {
    selectedTags.value.splice(index, 1)
  }
}

// 添加标签筛选
const addTagFilter = (tagId: string) => {
  if (!selectedTags.value.includes(tagId)) {
    selectedTags.value.push(tagId)
  }
}

// 获取用户个人信息
const fetchUserInfo = async () => {
  try {
    const response = await api.get('/api/v1/users/me')
    const data = response
    if (data.code === 0) {
      userInfo.value = data.data
    }
  } catch (e) {
    console.error('获取用户信息失败', e)
  }
}

// 获取作品数据
const fetchPosts = async () => {
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟数据
    const newPosts = generateMockPosts(12)
    posts.value = page.value === 1 ? newPosts : [...posts.value, ...newPosts]
    totalItems.value = 120 // 模拟总数
    hasMoreItems.value = posts.value.length < totalItems.value
  } catch (error) {
    console.error('获取作品失败', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多数据
const loadMoreData = async () => {
  if (loadingMore.value) return
  loadingMore.value = true
  page.value++
  fetchPosts()
}

// 处理点赞
const handleLike = (postId: number) => {
  const post = posts.value.find(p => p.id === postId)
  if (post) {
    post.isLiked = !post.isLiked
    post.likes += post.isLiked ? 1 : -1
  }
}

// 处理评论
const handleComment = (postId: number) => {
  console.log('打开评论', postId)
}

// 交互菜单
const postMenuItems = [
  [
    {
      label: '收藏',
      icon: 'i-heroicons-star',
      click: () => console.log('收藏')
    },
    {
      label: '分享',
      icon: 'i-heroicons-share',
      click: () => console.log('分享')
    }
  ],
  [
    {
      label: '举报',
      icon: 'i-heroicons-flag',
      click: () => console.log('举报')
    }
  ]
]

// 生成模拟作品数据
const generateMockPosts = (count: number) => {
  const mockPosts = []
  const tagsList = [
    [{ id: 'sunset', name: '日落' }, { id: 'mountains', name: '山脉' }],
    [{ id: 'beach', name: '海滩' }, { id: 'travel', name: '旅行' }],
    [{ id: 'city', name: '城市' }, { id: 'architecture', name: '建筑' }],
    [{ id: 'portrait', name: '人像' }, { id: 'vintage', name: '复古' }],
    [{ id: 'forest', name: '森林' }, { id: 'nature', name: '自然' }],
    [{ id: 'night', name: '夜景' }, { id: 'city', name: '城市' }]
  ]
  
  for (let i = 0; i < count; i++) {
    const id = Date.now() + i
    const randomAspectRatio = Math.random() * 0.5 + 0.5 // 生成0.5到1之间的随机宽高比
    
    mockPosts.push({
      id,
      title: `作品 ${id}`,
      description: `这是一个精美的摄影作品，展示了独特的视角和构图。`,
      imageUrl: `https://picsum.photos/seed/${id}/800/600`,
      aspectRatio: randomAspectRatio,
      author: {
        name: `用户${Math.floor(Math.random() * 1000)}`,
        avatar: `https://i.pravatar.cc/150?u=${id}`
      },
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toLocaleDateString('zh-CN'),
      tags: tagsList[Math.floor(Math.random() * tagsList.length)],
      likes: Math.floor(Math.random() * 200),
      comments: Math.floor(Math.random() * 50),
      isLiked: Math.random() > 0.7
    })
  }
  
  return mockPosts
}

// 模拟数据
const posts = ref([])

// 轮播图相关状态和方法
const currentSlide = ref(0)
const autoplayInterval = ref<NodeJS.Timeout | null>(null)
const featuredBoards = ref([
  {
    id: 1,
    title: '城市建筑摄影集',
    description: '探索现代都市建筑的几何美学，捕捉光影交织的瞬间。',
    images: [{
      img_url: 'https://images.unsplash.com/photo-1449034446853-66c86144b0ad?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80'
    }]
  },
  {
    id: 2,
    title: '自然风光摄影',
    description: '记录大自然的壮丽景色，展现地球最原始的美。',
    images: [{
      img_url: 'https://images.unsplash.com/photo-1493246507139-91e8fad9978e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80'
    }]
  },
  {
    id: 3,
    title: '人文街拍集',
    description: '捕捉城市中的人文瞬间，记录生活中的温暖故事。',
    images: [{
      img_url: 'https://images.unsplash.com/photo-1517457373958-b7bdd4587205?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2069&q=80'
    }]
  }
])

// 获取精品作品数据
const fetchFeaturedBoards = async () => {
  try {
    const response = await api.get('/api/v1/boards/featured')
    const data = response
    if (data.code === 0) {
      featuredBoards.value = data.data
    }
  } catch (e) {
    console.error('获取精品作品失败', e)
  }
}

// 轮播控制方法
const nextSlide = () => {
  currentSlide.value = (currentSlide.value + 1) % featuredBoards.value.length
}

const prevSlide = () => {
  currentSlide.value = currentSlide.value === 0 
    ? featuredBoards.value.length - 1 
    : currentSlide.value - 1
}

// 自动轮播
const startAutoplay = () => {
  autoplayInterval.value = setInterval(() => {
    nextSlide()
  }, 5000) // 每5秒切换一次
}

const stopAutoplay = () => {
  if (autoplayInterval.value) {
    clearInterval(autoplayInterval.value)
    autoplayInterval.value = null
  }
}

// 页面加载时初始化数据
onMounted(async () => {
  await Promise.all([fetchUserInfo(), fetchFeaturedBoards()])
  fetchPosts()
  startAutoplay()
})

onUnmounted(() => {
  stopAutoplay()
})

</script>

<style scoped>
/* 隐藏滚动条但保留滚动功能 */
.scrollbar-hide {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.scrollbar-hide::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.grid > div {
  animation: fadeIn 0.5s ease-out forwards;
}
</style>